package tsou.com.simple.realmtest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import io.realm.OrderedCollectionChangeSet;
import io.realm.OrderedRealmCollectionChangeListener;
import io.realm.Realm;
import io.realm.RealmAsyncTask;
import io.realm.RealmResults;
import tsou.com.simple.realmtest.adapter.MyAdapter;
import tsou.com.simple.realmtest.bean.Student;
import tsou.com.simple.realmtest.utils.UIUtils;

public class DeleteActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private ListView mListview;
    private List<String> titles = new ArrayList<>();
    private Realm mRealm;
    private RealmAsyncTask realmAsyncTask;
    private RealmResults<Student> students8;
    private RealmResults<Student> students9;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (students8 != null) {
            students8.removeChangeListener(callback);
            students8.removeAllChangeListeners();
        }
        if (students9 != null) {
            students9.removeChangeListener(callback);
            students9.removeAllChangeListeners();
        }
        if (realmAsyncTask != null && !realmAsyncTask.isCancelled()) {
            realmAsyncTask.cancel();
        }
        if (mRealm != null && !mRealm.isClosed()) {
            mRealm.close();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        mRealm = UIUtils.getRealmInstance();
        initData();
        initView();
        initListener();
    }

    private void initData() {
        titles.add("同步删除（一）:先查找到数据:deleteFromRealm(int index)");
        titles.add("同步删除（一）:先查找到数据:deleteFirstFromRealm()");
        titles.add("同步删除（一）:先查找到数据:deleteLastFromRealm()");
        titles.add("同步删除（一）:先查找到数据:deleteAllFromRealm()");
        titles.add("同步删除（二）:后查找到数据:deleteFromRealm(int index)");
        titles.add("同步删除（二）:后查找到数据:deleteFirstFromRealm()");
        titles.add("同步删除（二）:后查找到数据:deleteLastFromRealm()");
        titles.add("同步删除（二）:后查找到数据:deleteAllFromRealm()");
        titles.add("同步删除：deleteAll()");
        titles.add("同步删除：delete(xxx.class)");

        titles.add("异步删除:后查找到数据:deleteFromRealm(int index)");
        titles.add("异步删除:后查找到数据:deleteFirstFromRealm()");
        titles.add("异步删除:后查找到数据:deleteLastFromRealm()");
        titles.add("异步删除:后查找到数据:deleteAllFromRealm()");
        titles.add("异步删除：deleteAll()");
        titles.add("异步删除（推荐使用）：delete(xxx.class)");


        titles.add("推荐使用：异步查询，同步删除");
        titles.add("推荐使用：异步查询，异步删除");
    }

    private void initView() {
        mListview = (ListView) findViewById(R.id.listview);

        mListview.setAdapter(new MyAdapter(this, titles));
    }

    private void initListener() {
        mListview.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        switch (position) {
            default:
                break;
            case 0://同步删除（一）:先查找到数据:deleteFromRealm(int index)
                final RealmResults<Student> students = mRealm.where(Student.class).findAll();
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        students.deleteFromRealm(0);
                    }
                });
                break;
            case 1://同步删除（一）:先查找到数据:deleteFirstFromRealm()
                final RealmResults<Student> students1 = mRealm.where(Student.class).findAll();
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        students1.deleteFirstFromRealm();
                    }
                });
                break;
            case 2://同步删除（一）:先查找到数据:deleteLastFromRealm()
                final RealmResults<Student> students2 = mRealm.where(Student.class).findAll();
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        students2.deleteLastFromRealm();
                    }
                });
                break;
            case 3://同步删除（一）:先查找到数据:deleteAllFromRealm()
                final RealmResults<Student> students3 = mRealm.where(Student.class).findAll();
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        students3.deleteAllFromRealm();
                    }
                });
                break;
            case 4://同步删除（二）:后查找到数据:deleteFromRealm(int index)
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        RealmResults<Student> students = realm.where(Student.class).findAll();
                        students.deleteFromRealm(0);
                    }
                });
                break;
            case 5://同步删除（二）:后查找到数据:deleteFirstFromRealm()
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        RealmResults<Student> students = realm.where(Student.class).findAll();
                        students.deleteFirstFromRealm();
                    }
                });
                break;
            case 6://同步删除（二）:后查找到数据:deleteLastFromRealm()
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        RealmResults<Student> students = realm.where(Student.class).findAll();
                        students.deleteLastFromRealm();
                    }
                });
                break;
            case 7://同步删除（二）:后查找到数据:deleteAllFromRealm()
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        RealmResults<Student> students = realm.where(Student.class).findAll();
                        students.deleteAllFromRealm();
                    }
                });
                break;
            case 8://同步删除：deleteAll()
                //所有的数据库都会清除
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        realm.deleteAll();
                    }
                });
                break;
            case 9://同步删除：delete(xxx.class)
                //只会删除指定的数据库
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        realm.delete(Student.class);
                    }
                });
                break;

            case 10://异步删除:后查找到数据:deleteFromRealm(int index)
                realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        RealmResults<Student> students = realm.where(Student.class).findAll();
                        students.deleteFromRealm(0);
                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast("删除成功");
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        UIUtils.showToast("删除失败");
                    }
                });
                break;
            case 11://异步删除:后查找到数据:deleteFirstFromRealm()
                realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        RealmResults<Student> students = realm.where(Student.class).findAll();
                        students.deleteFirstFromRealm();
                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast("删除成功");
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        UIUtils.showToast("删除失败");
                    }
                });
                break;
            case 12://异步删除:后查找到数据:deleteLastFromRealm()
                realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        RealmResults<Student> students = realm.where(Student.class).findAll();
                        students.deleteLastFromRealm();
                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast("删除成功");
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        UIUtils.showToast("删除失败");
                    }
                });
                break;
            case 13://异步删除:后查找到数据:deleteAllFromRealm()
                realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        RealmResults<Student> students = realm.where(Student.class).findAll();
                        students.deleteAllFromRealm();
                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast("删除成功");
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        UIUtils.showToast("删除失败");
                    }
                });
                break;
            case 14://异步删除：deleteAll()
                //删除所有数据库
                realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        realm.deleteAll();
                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast("删除成功");
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        UIUtils.showToast("删除失败");
                    }
                });
                break;
            case 15://异步删除：delete(xxx.class)
                //删除指定的数据库
                realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        realm.delete(Student.class);
                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast("删除成功");
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        UIUtils.showToast("删除失败");
                    }
                });
                break;

            case 16://推荐使用：异步查询，同步删除
                students8 = mRealm.where(Student.class).findAllAsync();
                students8.addChangeListener(callback);
                break;
            case 17://推荐使用：异步查询，异步删除
                students9 = mRealm.where(Student.class).findAllAsync();
                students9.addChangeListener(callback1);
                break;
        }
    }


    /**
     * 异步操作的监听
     */
    private OrderedRealmCollectionChangeListener<RealmResults<Student>> callback = new OrderedRealmCollectionChangeListener<RealmResults<Student>>() {
        @Override
        public void onChange(RealmResults<Student> collection, OrderedCollectionChangeSet changeSet) {
            if (changeSet == null) {
                //第一次异步返回一个空的变更集。
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        realm.delete(Student.class);
                    }
                });
            } else {
                //每次RealmResults被更新时都会被调用
            }
        }
    };
    /**
     * 异步操作的监听
     */
    private OrderedRealmCollectionChangeListener<RealmResults<Student>> callback1 = new OrderedRealmCollectionChangeListener<RealmResults<Student>>() {
        @Override
        public void onChange(RealmResults<Student> collection, OrderedCollectionChangeSet changeSet) {
            if (changeSet == null) {
                //第一次异步返回一个空的变更集。
                realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        realm.delete(Student.class);
                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast("删除成功");
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        UIUtils.showToast("删除失败");
                    }
                });
            } else {
                //每次RealmResults被更新时都会被调用
            }
        }
    };
}
